<template>
  <a-modal
      v-model:visible="visible"
      :title="isEdit ? '编辑合集' : '创建合集'"
      :ok-text="isEdit ? '保存' : '创建'"
      @ok="handleOk"
      @cancel="handleCancel"
      :maskClosable="false"
      :width="800"
  >
    <a-form :model="form" ref="formRef" layout="vertical">
      <!-- 合集标题 -->
      <a-form-item label="合集标题" required>
        <a-input
            v-model:value="form.title"
            placeholder="请输入合集的标题"
            max-length="20"
            :disabled="isSubmitting"
        />
      </a-form-item>

      <!-- 合集简介 -->
      <a-form-item label="合集简介">
        <a-textarea
            v-model:value="form.desc"
            placeholder="请输入合集的简介"
            max-length="200"
            :auto-size="{ minRows: 3, maxRows: 5 }"
            :disabled="isSubmitting"
        />
      </a-form-item>

      <!-- 合集封面 -->
      <a-form-item label="合集封面" required>
        <a-upload
            v-model:file-list="coverFileList"
            :before-upload="beforeUpload"
            list-type="picture-card"
            accept="image/*"
            :max-count="1"
            :disabled="isUploading || isSubmitting"
        >
          <div v-if="coverFileList.length === 0">
            <upload-outlined />
            <div class="upload-text">上传合集封面</div>
          </div>
          <template #uploading>
            <div class="ant-upload-list-item-uploading-text">上传中...</div>
          </template>
        </a-upload>
        <div class="cover-tip">文件大小不超过5M，分辨率至少为100*100，1080*1080最佳</div>
      </a-form-item>

      <!-- 合集中作品 -->
      <a-form-item label="合集中作品" required>
        <a-button
            type="dashed"
            @click="openWorksSelector"
            class="add-works-btn"
            :disabled="isSubmitting"
        >
          <plus-outlined /> 选择作品
        </a-button>

        <div class="selected-works" v-if="form.works.length">
          <div class="selected-operate">
            <span class="selected-count">已选择 {{ form.works.length }} 个作品</span>
            <a-button
                type="text"
                danger
                @click="clearAllSelected"
                v-if="form.works.length > 0"
                :disabled="isSubmitting"
            >
              清空全部
            </a-button>
          </div>

          <div class="selected-works-container">
            <div
                v-for="(work, index) in form.works"
                :key="work.id"
                class="work-item"
            >
              <img :src="getWorkCover(work)" alt="作品封面" class="work-cover" />
              <div class="work-info">
                <span class="work-title">{{ work.worksName }}</span>
                <span class="work-meta">{{ work.duration }} | {{ formatDate(work.createTime) }}</span>
              </div>
              <a-icon
                  type="close"
                  class="delete-icon"
                  @click.stop="removeWork(index)"
                  :title="`移除 ${work.worksName}`"
                  :disabled="isSubmitting"
              />
            </div>
          </div>
        </div>
      </a-form-item>
    </a-form>

    <!-- 作品选择弹窗 -->
    <a-modal
        v-model:visible="worksSelectorVisible"
        title="选择作品"
        width="800px"
        @cancel="closeWorksSelector"
        :maskClosable="false"
        cancel-text="取消"
        @ok="confirmWorkSelection"
        :ok-button-props="{ disabled: isSubmitting }"
    >
      <!-- 搜索筛选 -->
      <div class="works-filter-bar">
        <a-input
            v-model:value="workSearchKeyword"
            placeholder="搜索作品名称"
            style="width: 300px; margin-right: 16px"
            allow-clear
            @pressEnter="handleSearch"
            :disabled="isLoadingWorks || isSubmitting"
        >
          <template #suffix>
            <SearchOutlined @click="handleSearch" :disabled="isLoadingWorks || isSubmitting" />
          </template>
        </a-input>
      </div>

      <!-- 作品列表 -->
      <div class="works-selector-list">
        <!-- 加载状态 -->
        <div v-if="isLoadingWorks" class="loading-container">
          <a-spin size="large" tip="加载作品中..." />
        </div>

        <!-- 空状态 -->
        <div v-else-if="filteredWorks.length === 0 && !isLoadingWorks" class="empty-container">
          <a-empty description="没有找到匹配的作品" />
          <a-button
              type="text"
              style="margin-top: 16px"
              @click="gotoUploadWorks"
              :disabled="isSubmitting"
          >
            去上传新作品
          </a-button>
        </div>

        <!-- 作品列表 -->
        <div v-else>
          <div
              v-for="work in filteredWorks"
              :key="work.id"
              class="selector-work-item"
              :class="{ 'selected': isWorkSelected(work.id) }"
              @click="toggleWorkSelection(work)"
          >
            <img :src="getWorkCover(work)" alt="作品封面" class="selector-work-cover" />
            <div class="selector-work-info">
              <h4 class="selector-work-title" :title="work.worksName">{{ work.worksName }}</h4>
              <div class="selector-work-meta">
                <span><calendar-outlined /> {{ formatDate(work.createTime) }}</span>
                <span><clock-circle-outlined /> {{ work.duration }}</span>
                <span v-if="work.isCharge === 1" class="charge-tag">收费</span>
                <span v-else class="free-tag">免费</span>
                <span :class="getStatusClass(work.status)" class="status-tag">
                  {{ getStatusText(work.status) }}
                </span>
              </div>
            </div>
            <a-checkbox
                :checked="isWorkSelected(work.id)"
                @change="(e) => handleWorkCheck(work, e.target.checked)"
                class="work-checkbox"
                :disabled="work.status !== 3 || isSubmitting"
            />
          </div>
        </div>
      </div>

      <!-- 选择器底部：分页和操作 -->
      <div class="selector-footer">
        <div class="selection-info">
          已选择 {{ form.works.length }} 个作品
          <span class="selection-limit">(最多选择 100 个)</span>
        </div>

        <div class="selector-pagination">
          <a-pagination
              v-model:current="currentPage"
              :pageSize="pageSize"
              :total="totalWorks"
              :showSizeChanger="true"
              :showQuickJumper="true"
              :showTotal="(total) => `共 ${total} 个作品`"
              @change="handlePageChange"
              @showSizeChange="handlePageSizeChange"
              :disabled="isLoadingWorks || isSubmitting"
          />
        </div>
      </div>
    </a-modal>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { Form, message, Modal } from 'ant-design-vue'
import {
  UploadOutlined, PlusOutlined, SearchOutlined,
  CalendarOutlined, ClockCircleOutlined
} from '@ant-design/icons-vue'
import type { UploadFile } from 'ant-design-vue'
import {getWorksList, getWorksListByUserId} from '@/api/media/bizWorksController';
import { uploadPic } from '@/api/media/bizFilesController';
// 引入接口
import { addCollection, updateCollection } from '@/api/media/bizCollectionController';

const minioUrl = import.meta.env.VITE_MINIO_URL
// 类型定义
interface BizWorks {
  id: number;
  worksName: string;
  coverFileUrl: string;
  duration: string;
  createTime: string;
  isCharge: number;
  status: number; // 1-草稿 3-已发布
}

// 后端接口参数类型（需与后端一致）
interface CollectionAddQuery {
  worksId: number[]; // 作品ID数组
  id: number | null;
  userId: number; // 实际项目中需从登录状态获取
  name: string; // 合集标题
  coverUrl: string; // 封面地址
  description: string; // 合集简介
  sortOrder: number | null;
  status: number | null;
}

// 核心状态
const visible = ref(false)
const isEdit = ref(false)
const formRef = Form.useForm()
const worksSelectorVisible = ref(false)
const isUploading = ref(false)
const isSubmitting = ref(false)

// 表单数据
const form = reactive({
  id: null as number | null, // 编辑时使用
  title: '',
  desc: '',
  cover: '',
  works: [] as BizWorks[],
  sortOrder: 0,
  status: 1
})

// 封面上传
const coverFileList = ref<UploadFile[]>([])
const beforeUpload = async (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage || !isLt5M) {
    message.error(!isImage ? '请上传图片文件' : '文件大小不能超过5MB')
    return false
  }

  isUploading.value = true;
  try {
    const response = await uploadPic({}, file);
    if (response.code === '00000' && response.data) {
      const uploadedFile: UploadFile = {
        uid: new Date().getTime().toString(),
        name: file.name,
        status: 'done',
        url: response.data.previewUrl,
      };
      coverFileList.value = [uploadedFile];
      form.cover = uploadedFile.url;
      await nextTick(); // 确保视图更新
      message.success('封面上传成功');
    } else {
      message.error('封面上传失败：' + (response.message || '未知错误'));
      return false;
    }
  } catch (error) {
    console.error('封面上传出错:', error);
    message.error('网络错误，封面上传失败');
    return false;
  } finally {
    isUploading.value = false;
  }
  return false;
}

// 作品选择
const userWorks = ref<BizWorks[]>([])
const isLoadingWorks = ref(false)
const workSearchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalWorks = ref(0)
const MAX_WORKS_LIMIT = 100

const fetchUserWorks = async () => {
  isLoadingWorks.value = true
  try {
    const response = await getWorksList({
      worksName: workSearchKeyword.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    });
    if (response.code === '00000' && response.data) {
      userWorks.value = response.data.list || [];
      totalWorks.value = response.data.total || 0;
    } else {
      message.error('获取作品列表失败: ' + (response.message || '未知错误'));
      userWorks.value = [];
      totalWorks.value = 0;
    }
  } catch (error) {
    message.error('网络错误，获取作品列表失败');
    userWorks.value = [];
    totalWorks.value = 0;
  } finally {
    isLoadingWorks.value = false;
  }
};

const filteredWorks = computed(() => userWorks.value);

const isWorkSelected = (workId: number) => form.works.some(work => work.id === workId)

const toggleWorkSelection = (work: BizWorks) => {
  if (work.status !== 3) {
    message.warning('只能选择已发布的作品');
    return;
  }
  if (form.works.length >= MAX_WORKS_LIMIT && !isWorkSelected(work.id)) {
    message.error(`最多只能选择${MAX_WORKS_LIMIT}个作品`);
    return;
  }
  const index = form.works.findIndex(item => item.id === work.id)
  if (index > -1) {
    form.works.splice(index, 1)
  } else {
    form.works.push(work)
  }
}

const handleWorkCheck = (work: BizWorks, checked: boolean) => {
  if (work.status !== 3) return;
  if (checked && form.works.length >= MAX_WORKS_LIMIT) {
    message.error(`最多只能选择${MAX_WORKS_LIMIT}个作品`);
    return;
  }
  const index = form.works.findIndex(item => item.id === work.id)
  if (checked && index === -1) {
    form.works.push(work)
  } else if (!checked && index > -1) {
    form.works.splice(index, 1)
  }
}

const handleSearch = () => {
  currentPage.value = 1;
  fetchUserWorks();
}

const handlePageChange = (page: number) => {
  currentPage.value = page;
  fetchUserWorks();
}

const handlePageSizeChange = (_, size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchUserWorks();
}

const openWorksSelector = () => {
  worksSelectorVisible.value = true;
  currentPage.value = 1;
  fetchUserWorks();
}

const closeWorksSelector = () => {
  worksSelectorVisible.value = false;
}

const confirmWorkSelection = () => {
  closeWorksSelector();
  if (form.works.length > 0) {
    message.success(`已选择 ${form.works.length} 个作品`);
  }
}

const gotoUploadWorks = () => {
  closeWorksSelector();
  emit('goto-upload');
}

const removeWork = (index: number) => {
  const removedWork = form.works.splice(index, 1)
  message.info(`已移除 "${removedWork[0].worksName}"`)
}

const clearAllSelected = () => {
  if (form.works.length === 0) return;
  Modal.confirm({
    title: '确认清空',
    content: `确定要移除所有已选的 ${form.works.length} 个作品吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      form.works = [];
      message.success('已清空所有已选作品');
    }
  });
}

// 辅助方法
// 辅助方法
const getWorkCover = (work: BizWorks) => {
  if (!work.coverFileUrl) return '';

  // 如果已经是完整URL，直接返回
  if (work.coverFileUrl.startsWith('http')) {
    return work.coverFileUrl;
  }

  // 否则才拼接minio地址（针对非完整URL的情况）
  const cleanCoverPath = work.coverFileUrl.replace(/^\//, '');
  const baseUrl = minioUrl.endsWith('/') ? minioUrl : `${minioUrl}/`;
  return `${baseUrl}${cleanCoverPath}`;
}

const formatDate = (dateString: string) => {
  if (!dateString) return '';
  return new Date(dateString).toLocaleDateString();
}

const getStatusText = (status: number) => ({ 1: '草稿', 3: '已发布' }[status] || '未知');
const getStatusClass = (status: number) => ({ 1: 'status-draft', 3: 'status-published' }[status] || 'status-unknown');

// 提交与取消
const handleOk = async () => {
  if (isSubmitting.value) return;
  isSubmitting.value = true;

  try {
    // 表单验证
    if (!form.title.trim()) {
      message.error('请输入合集标题');
      isSubmitting.value = false;
      return;
    }


    if (form.works.length === 0) {
      message.error('请选择至少一个作品');
      isSubmitting.value = false;
      return;
    }

    // 组装符合后端要求的参数
    const submitData = {
      worksId: form.works.map(work => work.id),
      id: form.id,
      name: form.title,
      coverUrl: form.cover,
      description: form.desc,
      sortOrder: form.sortOrder,
      status: form.status
    };

    // 根据编辑状态调用不同接口
    let response;
    if (isEdit.value) {
      response = await updateCollection(submitData);
    } else {
      response = await addCollection(submitData);
    }

    // 接口响应处理
    if (response?.code === '00000') {
      emit('save', submitData);
      visible.value = false;
      resetForm();
      message.success(isEdit.value ? '合集更新成功' : '合集创建成功');
    } else {
      message.error(`${isEdit.value ? '更新' : '创建'}失败：${response?.message || '未知错误'}`);
    }
  } catch (error) {
    console.error('提交表单出错:', error);
    message.error('提交失败，请重试');
  } finally {
    isSubmitting.value = false;
  }
}

const handleCancel = () => {
  emit('cancel');
  visible.value = false;
  resetForm();
}

// 重置表单
const resetForm = () => {
  form.id = null;
  form.title = '';
  form.desc = '';
  form.cover = '';
  form.works = [];
  form.sortOrder = 0;
  form.status = 1;
  coverFileList.value = [];
}

defineExpose({
  open: (isEditMode = false, initialData?: any) => {
    console.log('Modal open - isEditMode:', isEditMode, 'data:', initialData);

    // 设置编辑状态
    isEdit.value = isEditMode;
    visible.value = true;

    // 重置表单
    form.id = null;
    form.title = '';
    form.desc = '';
    form.cover = '';
    form.works = [];
    form.sortOrder = 0;
    form.status = 1;
    coverFileList.value = [];

    // 编辑模式填充数据
    if (initialData && isEditMode) {
      nextTick(() => {
        form.id = initialData.id;
        form.title = initialData.name || initialData.title || '';
        form.desc = initialData.description || initialData.desc || '';
        form.works = initialData.works || [];
        form.sortOrder = initialData.sortOrder || 0;
        form.status = initialData.status || 1;

        // 直接使用后端返回的完整封面URL
        if (initialData.coverUrl) {
          form.cover = initialData.coverUrl;
          coverFileList.value = [{
            uid: 'edit-' + Date.now(),
            name: 'cover.jpg',
            status: 'done',
            url: initialData.coverUrl,
            thumbUrl: initialData.coverUrl
          }];
        }
      });
    }
  },
})
// 事件发射
const emit = defineEmits<{
  (event: 'cancel'): void
  (event: 'save', data: any): void
  (event: 'goto-upload'): void
}>()
</script>

<style scoped>
.ant-form-item-label > label {
  color: #000000;
}
.upload-text {
  margin-top: 8px;
  color: #9eb6d0;
}

.cover-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #9eb6d0;
}

/* 添加作品按钮 */
.add-works-btn {
  width: 100%;
  margin-bottom: 16px;
  color: #fff;
  border-color: #4e6a8d;
  background-color: #4e6a8d;
}

.add-works-btn:hover {
  color: #fff;
  border-color: #3a506b;
  background-color: #3a506b;
}

/* 已选作品列表 */
.selected-works {
  margin-top: 10px;
}

.selected-operate {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.selected-count {
  font-size: 14px;
  color: #9eb6d0;
}

.selected-works-container {
  max-height: 240px;
  overflow-y: auto;
  padding-right: 8px;
}

.selected-works-container::-webkit-scrollbar {
  width: 6px;
}

.selected-works-container::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 3px;
}

.selected-works-container::-webkit-scrollbar-thumb {
  background: #4e6a8d;
  border-radius: 3px;
}

.work-item {
  display: flex;
  align-items: center;
  padding: 8px;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid #4e6a8d;
  border-radius: 4px;
  gap: 12px;
  margin-bottom: 8px;
  transition: all 0.2s;
}

.work-item:hover {
  background: rgba(255, 255, 255, 0.1);
}

.work-cover {
  width: 60px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
  flex-shrink: 0;
}

.work-info {
  flex: 1;
  min-width: 0;
}

.work-title {
  font-size: 14px;
  color: #000;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: block;
}

.work-meta {
  font-size: 12px;
  color: #9eb6d0;
}

.delete-icon {
  color: #ff4d4f;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.2s;
}

.delete-icon:hover {
  background: rgba(255, 77, 79, 0.1);
}

/* 作品选择器样式 */
.works-filter-bar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 10px;
}

.works-selector-list {
  max-height: 400px;
  overflow-y: auto;
  padding: 8px;
  margin-bottom: 16px;
}

.works-selector-list::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.works-selector-list::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 3px;
}

.works-selector-list::-webkit-scrollbar-thumb {
  background: #4e6a8d;
  border-radius: 3px;
}

.loading-container {
  width: 100%;
  padding: 60px 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.empty-container {
  text-align: center;
  padding: 40px 0;
}

:deep(.ant-empty-description) {
  color: #9eb6d0;
}

.selector-work-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-radius: 6px;
  margin-bottom: 8px;
  background: rgba(255, 255, 255, 0.05);
  cursor: pointer;
  transition: all 0.2s;
}

.selector-work-item:hover {
  background: rgba(255, 255, 255, 0.1);
}

.selector-work-item.selected {
  background: rgba(47, 128, 237, 0.2);
  border: 1px solid #2f80ed;
}

.selector-work-cover {
  width: 80px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 12px;
  flex-shrink: 0;
}

.selector-work-info {
  flex: 1;
  min-width: 0;
}

.selector-work-title {
  font-size: 16px;
  color: #000;
  margin: 0 0 8px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.selector-work-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  font-size: 12px;
  color: #9eb6d0;
  align-items: center;
}

.selector-work-meta span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.charge-tag {
  color: #ff4d4f;
  background: rgba(255, 77, 79, 0.1);
  padding: 0 4px;
  border-radius: 2px;
}

.free-tag {
  color: #52c41a;
  background: rgba(82, 196, 26, 0.1);
  padding: 0 4px;
  border-radius: 2px;
}

.status-tag {
  padding: 0 4px;
  border-radius: 2px;
  font-size: 12px;
}

.status-draft {
  color: #faad14;
  background: rgba(250, 173, 20, 0.1);
}

.status-published {
  color: #52c41a;
  background: rgba(82, 196, 26, 0.1);
}

.status-unknown {
  color: #8c8c8c;
  background: rgba(140, 140, 140, 0.1);
}

.work-checkbox {
  margin-left: auto;
  color: #2f80ed;
}

.selector-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding-top: 12px;
  border-top: 1px solid #4e6a8d;
  flex-wrap: wrap;
  gap: 12px;
}

.selection-info {
  color: #c9d8e9;
  font-size: 14px;
}

.selection-limit {
  color: #9eb6d0;
  font-size: 12px;
  margin-left: 8px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .ant-modal-content {
    width: 95% !important;
  }

  .selector-work-meta {
    gap: 8px;
  }

  .selector-footer {
    flex-direction: column;
    align-items: stretch;
  }

  .selector-work-item {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>